//跟进计划列表
var $followPlanLogTable = $('#followPlanLogForm');
//防止表头与表格不对齐
$(window).resize(function () {
    $followPlanLogTable.bootstrapTable('resetView');
});

$(function () {
    // 初始化日期选择控件
    $('#startDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    // 初始化日期选择控件
    $('#endDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //初始化跟进计划列表
    followPlanFormLogList();

    // getCustomerSelect();

    ifSys();

    loadAllCompanyList("companyName");
});

function selectTime(time){
    if (time == 'all') {
        $('.all').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("");
        followPlanFormLogList();
    }
    if (time == 'today') {
        $('.today').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("thisDay");
        followPlanFormLogList();
    }
    if (time == 'week') {
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisWeek");
        followPlanFormLogList();
    }
    if (time == 'month') {
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisMonth");
        followPlanFormLogList();
    }
    if (time == 'year') {
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisYear");
        followPlanFormLogList();
    }
}

function followPlanFormLogList() {
//先销毁表格
    $followPlanLogTable.bootstrapTable('destroy');
    $followPlanLogTable.bootstrapTable({
        classes: 'table table-bordered table-hover',
        url: '/clueFollow/selectClueFollowList',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'clueFollowId',
        idField: 'clueFollowId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'clueFollowId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat,width:120},
            {title: '客户名称',field: 'customerName', align: 'left', valign: 'middle',width: 350,formatter: customerNameFormat},
            // {title: '联系人', field: 'contactName', align: 'left', valign: 'middle',width:150,formatter: contactNameFormat},
            {title: '所有人', field: 'createPeopleName', align: 'left', valign: 'middle', visible: false},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle', visible: false},
            {title: '跟进时间', field: 'followTm', align: 'left', valign: 'middle',width:150, sortable: true},
            {title: '标签', field: 'tag', align: 'left', valign: 'middle', sortable: true,formatter: tagFormat},
            {title: '操作',field: 'operate',align: 'right',formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#orderTableList').css({
                minWidth: $('#orderTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 导入框
 */
function showImportFollowModal() {
    $('#importFollowModal').modal('show');
}

/**
 * 下载模板
 */
function downFollowTemplate() {
    var url="/clueFollow/downTemplate";
    window.location.href=encodeURI(encodeURI(url));
}


/**
 * 导入
 */
function importFollow() {
    if(!document.getElementById('importFollowFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    var fileName = document.getElementById('importFollowFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importFollowFile")[0].files[0]);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX"||fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/clueFollow/importExcel',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            success:(function(data) {
                if(data.code == "000000"){
                    $.alert({
                        title: '提示',
                        content: content,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importFollowFile").val("");
                                    $followPlanLogTable.bootstrapTable('refresh');
                                }
                            }
                        }
                    });
                    $('#importFollowModal').modal('hide');
                    $("#importFollowModal").val("");
                }else if(data.code == "CI0001"){
                    $.alert({
                        title: '提示',
                        content: data.message,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importFollowFile").val("");
                                }
                            }
                        }
                    });
                }else{
                    $.alert("导入失败");
                    $("#importFollowFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importContractFile").val("");
            })
        });
    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx或.xls文件！',
        });
    }
}


/**
 * 取消导入
 */
function cancelImportFollow() {
    $("#importFollowFile").val("");
}



/**
 * 点击客户姓名跳转客户详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerNameFormat(value, row, index) {
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else {
        if(row.customerType == 1){//个人客户
            return'<a href="#" onclick="contactNameDetail(\'' + row.customerName + '\',\'' + row.contactPersonPhone + '\', \'' + row.customerId + '\')">'+value+'</a>';
        }else{//企业客户
            return'<a href="#" onclick=customerDetail("' + row.customerId + '")>'+value+'</a>';
        }
    }

}

function  customerDetail(customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '客户详情',
        url: "/front/user/customerManager/customerDetail?customerId=" + customerId
    },true);
}

/**
 * 我的客户(个人客户)--客户名称列点击事件(客户详情)
 * @param customerName
 * @param contactPersonPhone
 */
function contactNameDetail (customerName, contactPersonPhone, customerId) {
    var contactId = "";

    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getCustomerIdAndContactNameAndAccountId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId,
            contactName: customerName,
            contactInformation : contactPersonPhone,
            contactNature : '1'
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }else{
                    $.alert("数据有问题,请重试!");
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}

/**
 * 点击联系人姓名跳转联系人详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactNameFormat(value, row, index) {
    if(row.followSource == 6 && row.personName){//一机多用联系人显示(直接从cp_clue_follow表获取)
        return '<span href="JavaScript:void(0);">'+row.personName+ '</span>';
    }else{
        if(value == null) {
            return '<span href="JavaScript:void(0);">-</span>';
        }else {
            return '<a href="JavaScript:void(0);" onclick=\'contactDetail(\"'+row.contactId+'")\'>'+value+'</a>';
        }
    }


}

function  contactDetail(contactId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '联系人详情',
        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
    },true);
}


function searchOrderList(type) {
    $("#dateType").val("");
    if (type === 1) {//普通条件查询
        $followPlanLogTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams2});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetOrderQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#orderNumberMin').val('');
        $followPlanLogTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }
    //selectTime('all')
}

function tagFormat(value){
    if(value != null && value != ''){
        var valueList =  value.split(',');
        if(valueList.length>5){
            valueList = valueList.slice(0,5)
        }
        let html = '';
        $.each(valueList,function(index,item){
            html +=  '<span class="tags">'+ item +'</span>';
        });

        return html;
    }else if(value == null || value  == ''){
        return '-'
    }


}


function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.contactName = $.trim($('#contactPerson').val());//联系人
    params.startDate = $.trim($('#startDate').val());//开始计划日期
    params.endDate = $.trim($('#endDate').val());//截止计划日期
    params.companyId = $.trim($('#companyName').val());//公司
    params.createPeopleName = $('#createPeopleName').val();//所属人
    params.dateType = $('#dateType').val();
    params.followWay = $('#followWay').val();
    return params;
}

function queryParams2(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.dateType = $('#dateType').val();
    params.followType = $('#followType').val();
    return params;
}

//重置高级查询
function clearAllData() {
    $('#customerName2').val('');
    $('#contactPerson').val('');
    $('#startDate').val('');
    $('#endDate').val('');
    $('#createPeopleName').val('');
    $('#company').val('');
    $('#followWay').val('');

}
/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" onclick="getFollowInfo(\''+row.clueFollowId+'\',\''+row.followWay+'\')">详情</button>';
    html += '</ul></div>';
    return html;
}

//跟进详情
function getFollowInfo(clueFollowId,followWay) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : "跟进详情",
        url : "/front/customerManager/customerFollowRecordDetail?followWay="+followWay+"&clueFollowId="+ clueFollowId
    }, true);
}


function indexFormat(value, row, index) {
    return index + 1;
}


//删除计划
function delFollowPlan(cpFollowPlanId) {
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/followPlan/deleteFollowPlan',
        cache : false,
        data:{"cpFollowPlanId":cpFollowPlanId
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '取消成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                window.location.reload();
                            }
                        }
                    }
                });
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

// 跳转线上线下电话跟进   跟进方式：1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
function goOnline(name) {
    var type = '';
    var title = '跟进';
    var source = '1';//从哪跳转到跟进页面（0：线索；1：客户）
    // 线上电话
    if (name == 'online') {
        type = "1";
        title = '客户跟进-线上电话';
    }
    // 拜访
    if (name == 'visit') {
        type = "2";
        title = '客户跟进-拜访';
    }
    // 微信
    if (name == 'WeChat') {
        type = "3";
        title = '客户跟进-微信交流';
    }
    // 线下电话
    if (name == 'offline') {
        type = "4";
        title = '客户跟进-线下电话';
    }
    // 电子邮件
    if (name == 'email') {
        type="5";
        title = '客户跟进-电子邮件';
    }
    // 陪访
    if (name == 'accompanyingVisit') {
        type = "6";
        title = '客户跟进-陪访';
    }
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : title,
        url : "/front/followPlanManager/clueFollow?type="+ type +"&source=" +source
    }, true);
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    // 跟进
    'click #followUp': function (e, value, row, index) {
        // followUpFun(row);
    },
};

function ifSys() {
    var v=$.trim($('#isAdmin').val());
    if (v == "false"){
        if ( $("#qx").val() == 1){
            $('#companyNameDiv').css('display', 'none');
            $followPlanLogTable.bootstrapTable('showColumn', "createPeopleName");
        }
    }else if (v){
        $followPlanLogTable.bootstrapTable('showColumn', "createPeopleName");
        $followPlanLogTable.bootstrapTable('showColumn', "companyName");
    }
}

/**
 * 加载全部公司信息并且赋值到select框
 */
function loadAllCompanyList(name) {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">请选择</option>';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $('#'+name).html("");
            $('#'+name).append(companyOptionHtml);
            $('#'+name).selectpicker('refresh');
        }
    });
}